"""
Ansible Management Serializers
"""
from rest_framework import serializers
from .models import AnsibleInventory, AnsibleCredential, AnsiblePlaybook, AnsibleJob
from cmdb.models import Host


class AnsibleInventorySerializer(serializers.ModelSerializer):
    """Ansible配置序列化器"""
    host_count = serializers.SerializerMethodField()
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    hosts = serializers.PrimaryKeyRelatedField(many=True, queryset=Host.objects.all(), required=False)
    
    class Meta:
        model = AnsibleInventory
        fields = ['id', 'name', 'description', 'host_address', 'ssh_port', 'ssh_user',
                  'auth_type', 'ssh_password', 'ssh_key', 'ansible_config_path', 
                  'inventory_path', 'is_enabled', 'is_default', 'hosts', 'host_count', 
                  'variables', 'created_by', 'created_by_name', 'created_at', 'updated_at']
        read_only_fields = ['created_by', 'created_at', 'updated_at']
        extra_kwargs = {
            'ssh_password': {'write_only': True},
            'ssh_key': {'write_only': True},
        }
    
    def get_host_count(self, obj):
        return obj.hosts.count()
    
    def to_representation(self, instance):
        """隐藏敏感信息"""
        ret = super().to_representation(instance)
        if instance.ssh_password:
            ret['ssh_password'] = '******'
        if instance.ssh_key:
            ret['ssh_key'] = '******'
        return ret
    
    def create(self, validated_data):
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class AnsibleCredentialSerializer(serializers.ModelSerializer):
    """Ansible凭据序列化器"""
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    
    class Meta:
        model = AnsibleCredential
        fields = ['id', 'name', 'credential_type', 'username', 'password', 'ssh_key',
                  'become_method', 'become_user', 'become_password', 'description',
                  'created_by', 'created_by_name', 'created_at', 'updated_at']
        read_only_fields = ['created_by', 'created_at', 'updated_at']
        extra_kwargs = {
            'password': {'write_only': True},
            'ssh_key': {'write_only': True},
            'become_password': {'write_only': True},
        }
    
    def create(self, validated_data):
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)
    
    def to_representation(self, instance):
        """隐藏敏感信息"""
        ret = super().to_representation(instance)
        if instance.password:
            ret['password'] = '******'
        if instance.ssh_key:
            ret['ssh_key'] = '******'
        if instance.become_password:
            ret['become_password'] = '******'
        return ret


class AnsiblePlaybookSerializer(serializers.ModelSerializer):
    """Ansible Playbook序列化器"""
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    inventory_name = serializers.CharField(source='inventory.name', read_only=True)
    credential_name = serializers.CharField(source='credential.name', read_only=True)
    
    class Meta:
        model = AnsiblePlaybook
        fields = ['id', 'name', 'description', 'content', 'status', 'inventory', 'inventory_name',
                  'credential', 'credential_name', 'variables', 'tags', 
                  'created_by', 'created_by_name', 'created_at', 'updated_at']
        read_only_fields = ['created_by', 'created_at', 'updated_at']
    
    def create(self, validated_data):
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class AnsibleJobSerializer(serializers.ModelSerializer):
    """Ansible任务序列化器"""
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    playbook_name = serializers.CharField(source='playbook.name', read_only=True)
    inventory_name = serializers.CharField(source='inventory.name', read_only=True)
    credential_name = serializers.CharField(source='credential.name', read_only=True)
    duration = serializers.SerializerMethodField()
    
    class Meta:
        model = AnsibleJob
        fields = ['id', 'job_type', 'playbook', 'playbook_name', 'inventory', 'inventory_name',
                  'credential', 'credential_name', 'module', 'args', 'target_hosts', 'extra_vars', 
                  'status', 'result', 'stdout', 'stderr', 'start_time', 'end_time', 'duration',
                  'created_by', 'created_by_name', 'created_at']
        read_only_fields = ['status', 'result', 'stdout', 'stderr', 'start_time', 'end_time', 
                            'created_by', 'created_at']
    
    def get_duration(self, obj):
        """计算执行时长"""
        if obj.duration:
            return obj.duration
        if obj.start_time and obj.end_time:
            duration = (obj.end_time - obj.start_time).total_seconds()
            return f"{duration:.2f}s"
        return None
    
    def create(self, validated_data):
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)
